import sys
sys.path.append("..")   #也可以这样
from base.kuaishou import Base
from loguru import logger
from pymongo import MongoClient, UpdateOne
from base.base_tools import Mymongo, determine_video_orientation
from pandas import DataFrame
import requests
from base.base_tools import get_date_x_days_ago,get_datetime_x_days_ago

class Kuaishou_tools(Base):
    def __init__(self, account,advertiser_id) -> None:
        # 调用父类的构造函数
        super().__init__(account)
        self.advertiser_id = advertiser_id
        
    def 获取模板(self,app="素材神器",template_name="安卓01"):
        with Mymongo() as mongo:
            template_data = mongo.db["广告发布模板"].find_one({"产品":app,"名称":template_name},{"_id":0})
            return template_data
    
    def 创建广告组(self,template_data_all,campaign_id,bid):
        template_data = template_data_all["广告组"]
        unit_name = get_datetime_x_days_ago(0)
        template_data["advertiser_id"] = self.advertiser_id
        template_data["unit_name"] = unit_name
        template_data["cpa_bid"] = bid * 1000
        template_data["campaign_id"] = campaign_id
        template_data["begin_time"] = get_date_x_days_ago(0) #直接获取今日的数据


        url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/unit/create"
        # print (template_data)

        return requests.post(url,headers=self.headers,json=template_data).json()
    
    # 需要单独测试一下是否可行
    def 创建程序化创意(self,template_data_all,unit_id=3612408144,package_name="AI创建测试",captions=[],photo_list=[]):
        '''
        # 传入模板数据,然后开始进行创建
        template_data_all = self.获取模板(app=app,template_name=template_name)["创意"]
        captions: 广告语标题
        photo_list:[
                    {
                        "creative_material_type": 1,  # 素材类型需要写好,或是直接计算好就可以了
                        "photo_id": 5259923012780529003,
                        "cover_image_url": "https://p2.a.yximgs.com/upic/2024/01/15/17/BMjAyNDAxMTUxNzA1MjdfMjEzNjA0NzM0OF8xMjIxNDEwNDI0NDBfMF8z_B238160f80d712b5d839f9ca687d3abfa.jpg?tag=1-1705386928-unknown-0-rphvf9ry2x-887351e36028a690&clientCacheKey=3xiqdyz5wn5k88g.jpg&di=7829e2cb&bp=10000",
                    }]
        '''
        # 从广告模板中获取创意的模板
        template_data = template_data_all["创意"]
        template_data["advertiser_id"] = self.advertiser_id
        template_data["unit_id"] = unit_id
        template_data["package_name"] = package_name
        template_data["captions"] = captions
        template_data["photo_list"] = photo_list
        
        # print (template_data)

        url = "https://ad.e.kuaishou.com/rest/openapi/gw/dsp/advanced_creative/create"
        return requests.post(url,headers=self.headers,json=template_data).json()
    
    
    def 更新素材的关联创意数(self):
        # 更新计划的关联数量
        with Mymongo() as mongo:

            # 获取所有的素材列表
            photo_id_data = mongo.db["素材列表"].find({"advertiser_id":self.advertiser_id},
                                                {"photo_id":1,"_id":0,"advertiser_id":1})
            datas = list(photo_id_data)
            if not datas:
                logger.warning("没有素材可以更新")
                return 
            photo_ids_list = DataFrame(datas)["photo_id"].to_list()
            # 批量获取关联素材的数据
            json_data_photo = self.get_video_relate_creatives_data_num(self.advertiser_id,photo_ids_list)
            
            # 构建批量更新操作列表
            update_operations = []
            for data in json_data_photo:
                query = {'advertiser_id': data['advertiser_id'], 'photo_id': data['photo_id']}
                
                # 根据 related_creatives_count 的值设置 material_status
                material_status = "新素材" if data['related_creatives_count'] == 0 else "老素材"
                
                update_data = {'$set': {'related_creatives_count': data['related_creatives_count'], 
                                        'material_status': material_status}}
                update_operations.append(UpdateOne(query, update_data))

            # 执行批量更新
            result = mongo.db["素材列表"].bulk_write(update_operations)

            # 输出更新结果
            print(f"总共更新了 {result.modified_count} 条记录。")
                
    
    def 采集素材并更新关联数据(self):
        b = Base(self.account) 
        # 获取所有的素材
        b.update_all_get_video_list(self.advertiser_id)
        self.更新素材的关联创意数()
        
    def 获取创意发布素材(self,max_video_count_limit=5,sample_size=15,apply_outer_loop_native_filter=True):
        
        apply_outer_loop_native_filter = True  # 是否只取原生素材?
        
        with Mymongo() as mongo:
            match_condition = {"advertiser_id": self.advertiser_id, "max_video_count": {"$lte": max_video_count_limit}}
            if apply_outer_loop_native_filter:
                match_condition["outer_loop_native"] = {"$in": [1, 3]}
            
            
            pipeline = [
                {"$match": match_condition},
                {"$sample": {"size": sample_size}},
                {"$project": {"_id": 0, "photo_id": 1, "cover_url": 1, "height": 1, "width": 1}}
            ]
            video_data = mongo.db["素材列表"].aggregate(pipeline)
            item_list = []
            for data in video_data:
                item = {
                "creative_material_type":determine_video_orientation(data["width"],data["height"]),
                "photo_id": int(data["photo_id"]),
                "cover_image_url": data["cover_url"]
                    }
                item_list.append(item)
            return item_list
    